package com.aischool.service;

import java.util.ArrayList;
import java.util.List;

import com.aischool.utils.StateEnum;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

public class AiArticlecatService {

	public final String CK_CacheName = "CacheArticle";
	public final String CK_Ai_Article_Cat_TypeId_Pre = "CK_Ai_Article_Cat_TypeId_";
	
	public String getCacheKey(int type_id, int cat_state) {
		return CK_Ai_Article_Cat_TypeId_Pre + type_id + "_cat_state_" + cat_state;
	}
	
	
	public List<Record> getAll(int type_id, int cat_state){
		String sql = "SELECT a.*, b.type_name "
				+ "FROM ai_article_cat a "
				+ "INNER JOIN ai_article_type b ON b.type_id = a.type_id "
				+ "WHERE a.cat_state ";
		if (cat_state == StateEnum.ALL.getState()) {
			sql += " >= 0 ";
		}else {
			sql += " = " + cat_state;
		}
		if (type_id > 0) {
			sql += " AND a.type_id = " + type_id;
		}
//		return Db.findByCache(CK_CacheName, getCacheKey(type_id, cat_state), 
//				sql + " ORDER BY a.parent_id, a.cat_sort, a.cat_id");
		return Db.find(sql + " ORDER BY a.parent_id, a.cat_sort, a.cat_id");
	}
	
	public List<Record> getOrgCat(int org_id, int type_id, int cat_state){
		String sql = "SELECT a.*, b.type_name "
				+ "FROM ai_article_cat a "
				+ "INNER JOIN ai_article_type b ON b.type_id = a.type_id "
				+ "INNER JOIN ai_app_article_cat c ON c.cat_id = a.cat_id "
				+ "WHERE a.cat_state = ? AND c.org_id = ? ";
		List<Object> listparams = new ArrayList<Object>();
		listparams.add(cat_state);
		listparams.add(org_id);
		if (type_id > 0) {
			sql += " AND a.type_id = ? ";
			listparams.add(type_id);
		}
		sql += "ORDER BY a.parent_id, a.cat_sort, a.cat_id";
//		return Db.findByCache(CK_CacheName, getCacheKey(type_id, cat_state), sql, 
//				listparams.toArray());
		return Db.find(sql, listparams.toArray());
	}

	
	public Record getFirst(int cat_id) {
		return Db.findFirst("SELECT a.*, b.type_name FROM ai_article_cat a INNER JOIN ai_article_type b ON b.type_id = a.type_id WHERE a.cat_id = ?", cat_id);
	}
	
	public boolean updateState(int cat_id, int cat_state) {
		int ir = Db.update("UPDATE ai_article_cat SET cat_state = ? WHERE cat_id = ?", cat_state, cat_id);
		if (ir > 0) {
			removeCache();
		}
		return ir>0;
	}
	public boolean del(int cat_id) {
		int ir = Db.update("DELETE FROM ai_article_cat WHERE cat_id = ?", cat_id);
		if (ir > 0) {
			removeCache();
		}
		return ir>0;
	}
	
	public void removeCache() {
		CacheKit.removeAll(CK_CacheName);
	}
}
